<?php

namespace app\index\model;

use think\Model;

class Goods extends Model
{
    protected $table='goods';


    public function img(){
        return $this->hasMany('GoodsImg','goods_id','id');
    }

    public function attribute(){
        return $this->hasMany('Attribute','goods_id','id');
    }

    public function comments(){
        return $this->hasMany('Comments','goods_id','id');
    }

    public function brand(){
        return $this->belongsTo('Brand','brand_id','id');
    }

    public  function shopCart(){
        return $this->hasMany('ShopCart','goods_id','id');
    }
    /**
     * 删选的条件
     * @param $where
     * @return \think\Paginator
     */
    public function getConditionGoods($where,$orders){
        if (!empty($where['id'])){
            $data['type_id']=$where['id'];
        }
        if (!empty($where['brand_id'])){
            $data['brand_id']=$where['brand_id'];
        }


        if(!empty($orders['inventory'])) {
            $order['inventory'] = 'desc';
        }
        if(!empty($orders['purchase_price'])) {
            $order['purchase_price'] = 'desc';
        }
        if(!empty($orders['time'])) {
            $order['time'] = 'desc';
        }
        $order['goods.id'] = 'desc';
        $result=$this->where($data)
            ->order($order)
            ->withCount('comments')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->paginate(4);
        return $result;
    }

    /**
     * 获取最热的商品
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getHotGoods($id){
        $hot=$this->where('type_id',$id)
            ->where("attr_status",3)
            ->with('attribute')
            ->limit(3)
            ->select();
        return $hot;
    }

    /**
     * 获取最新的商品
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getNewGoods($id){
        $new=$this->where('type_id',$id)
            ->where("attr_status",2)
            ->with('attribute')
            ->limit(3)
            ->select();

        return $new;
    }

    /**
     * 商品详情
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getGoods($id){
        $goods=$this->where('goods.id',$id)
            ->join('attribute','goods.id=attribute.goods_id')
            ->withCount('comments')
            ->with('brand')
            ->with('img')
            ->group('goods.id')
            ->find();
        return $goods;
    }

    public function getAllGoods($id,$attr){

        $goods=$this->where('goods.id',$id)
            ->join('attribute','goods.id=attribute.goods_id')
            ->withCount('comments')
            ->with('brand')
            ->with('img')
            ->group('goods.id')
            ->where('attribute.id',$attr)
            ->find();
        return $goods;
    }
}
